local DataModel = import(".DataModel")
local Player = class("Player",DataModel)

local secondsOfOneDay = 24*60*60

function Player:ctor()
	Player.super.ctor(self)

	-- 是否第一次全量读取了数据
	self._isInit = false

	self._charmLastUpdateTime = nil -- 好运钥匙最近的上一次刷新时间戳
	self:clear()
end

function Player:clear()
	-- 基础信息
	self.uid = 0
	self.name = ""
	self.level = 1
	self.exp = 0
	self.expDaily = 0
	self.expPool = 0

	self.raceID = 0		--种族
    self.classID = 0	--职业
	self.gender = 1		--性别
	self.faceID = 0		--脸型
	self.hairID = 0		--发型（头部去除了脸部）
	self.hairColorID = 0	--发色
	self.luck = 0	--幸运值
	self.combatPower = 0	--战斗力
	self.mountUID = "" -- mountId和mountUID一样的，mountUID是string
	self.skillChooseID = 0 	--选中的技能方案(0-n) 专精id
    self.charm = {num=0, useDailyNum=0, lastUseTime=0}	-- 好运符
    self.mapId = 0
	self.position = 0
	self.achievementPoint = 0
	-- self.partnerID = 0
	self.partners = {}
	self.isPayOpen = false --充值功能是否开放
	self.rewardLevel = 0 --奖励等级
	self.recharge = 0 -- 累计充值

    self._applyEnable = true -- 是否可以apply，目前仅用在 exp/level
    self._applyDict = {} -- 不能发送消息期间的更新数据
    self._charmLastUpdateTime = nil -- 好运钥匙最近的上一次刷新时间戳
end

function Player:setHasInit()
	self._isInit = true
end


function Player:updatePartner(value)
	local oldPartners = self.partners
	local ps = {}
	for k , v in pairs(value.partners) do
		table.insert(ps,  {id = v.ID, raceId = v.RaceId, combatPower = v.CombatPower})
	end
	self.partners = ps
	UD.partnersData:updateByPlayer(oldPartners, self.partners)
end

function Player:read(value,dispatchEvent)
	self:update("uid",value,dispatchEvent)
	self:update("name",value,dispatchEvent)
	self:update("raceID",value,dispatchEvent)
	self:update("classID",value,dispatchEvent)
	self:update("gender",value,dispatchEvent)
	self:update("hairID",value,dispatchEvent)
	self:update("faceID",value,dispatchEvent)
	self:update("hairColorID",value,dispatchEvent)
	self:update("mountUID",value,dispatchEvent)
	self:update("achievementPoint",value,dispatchEvent)
	self:update("expDaily",value,dispatchEvent)
	self:update("expPool",value,dispatchEvent)
	-- self:update("partnerID",value,dispatchEvent)
	self:update("isPayOpen",value,dispatchEvent)
	self:update("rewardLevel",value,dispatchEvent)
	self:update("recharge", value,dispatchEvent)
	self:updatePartner(value)
	if not self._applyEnable and dispatchEvent then
		if value.exp and value.exp ~= self.exp then
			self._applyDict["exp"] = {data=value, dispatchEvent=dispatchEvent}
		end

		if value.level and value.level ~= self.level then
			self._applyDict["level"] = {data=value, dispatchEvent=dispatchEvent}
		end

		if (value.exp and value.exp ~= self.exp) or (value.level and value.level ~= self.level) then
			self._applyDict["expAndLevel"] = {old = {exp = self.exp,level = self.level}, new = {exp = value.exp,level = value.level}}
		end
	else
		if dispatchEvent and ((value.exp and value.exp ~= self.exp) or (value.level and value.level ~= self.level)) then
			self:dispatchChange("expAndLevel",{exp = self.exp,level = self.level},{exp = value.exp,level = value.level})
		end

		self:update("exp",value,dispatchEvent)
		self:update("level",value,dispatchEvent)
	end

	self:update("luck",value,dispatchEvent)
	self:update("combatPower",value,dispatchEvent)

	self:update("skillChooseID",value,dispatchEvent)
	--temp del

	-- TODO csg player里面都是单层的数据，这个数据不应该放在这里
	if value.charm then
		local charm = value.charm
		if self.charm.num ~= charm.num or
			self.charm.useDailyNum ~= charm.useDailyNum or
			self.charm.lastUseTime ~= charm.lastUseTime then

			self.charm.num = charm.num
			self.charm.useDailyNum = charm.useDailyNum
			self.charm.lastUseTime = charm.lastUseTime

			if dispatchEvent then
				self:dispatchChange("charm", self.charm, self.charm)
			end
		end
	end
	self:update("mapId", value, dispatchEvent)
	self:update("position", value, dispatchEvent)
end

function Player:apply(oper,dispatchEvent)
	-- 目前服务器有bug，创建角色第一次登陆时会先收到apply，再收到整个UserData包
	if not self._isInit then return end
	self:read(oper,dispatchEvent)
end

function Player:setApplyEnable(b)
	self._applyEnable = b
	if b then
		for k,v in pairs(self._applyDict) do
			if k == "expAndLevel" then
				self:dispatchChange(k,v.old,v.new)
			else
				self:update(k, v.data, v.dispatchEvent)
			end
		end

		self._applyDict = {}
	end
end

function Player:getUserBaseInfo()
	local info = UserBaseInfo.new(self)
	info.mountID = tonumber(self.mountUID)
	info.specialistID = tonumber( self.skillChooseID )
	return info
end

function Player:getClassName()
	return GD:getClassName(self.classID)
end

function Player:getClassIcon(index)
	return GD:getClassIcon(self.classID, index)
end

-- 基础属性配置表
function Player:getBaseConf()
	if not self._baseConf then
		self._baseConf = GD:queryProBase(self.classID)
	end
	return self._baseConf
end

local BASE_ATTR_NAMES_1 = {"bahp", "baar", "bamr", "baad", "bacritrt"}
local BASE_ATTR_NAMES_2 = {"bahp", "baar", "bamr", "baap", "bacritrt"}
-- 获取最基本的属性名称（有物攻／法攻的区别）
function Player:getBaseAttrNames()
	if self.classID == 1 or self.classID == 3 or self.clasID == 4 then
		return BASE_ATTR_NAMES_1
	else
		return BASE_ATTR_NAMES_2
	end
end

-- 帮助函数
local function parseDailyUpdateTime()
	local curTime = math.floor(app.session:getServerTime() or app:getTime())
	local startHour = tonumber(GD:getSystemPar("daystartsat", 5))
	local tab = os.date("*t", curTime)
	local curHour = tab.hour
	tab.hour = startHour
	tab.min = 0
	tab.sec = 0

	return curTime, tab, curHour, startHour
end

-- 更新好运钥匙最近的上一次刷新时间戳
function Player:updateCharmLastUpdateTime()
	local _, tab, curHour, startHour = parseDailyUpdateTime()

	self._charmLastUpdateTime = os.time(tab) -- 上次的刷新时间
	if curHour < startHour then
		-- 刷新时间之前
		self._charmLastUpdateTime = self._charmLastUpdateTime - secondsOfOneDay
	end
end

-- 跨天刷新好运钥匙数量
function Player:onDailyUpdate()
	local curTime, tab = parseDailyUpdateTime()

	if tonumber(GD:getSystemPar("charmRefresh", 4)) == ( tonumber( tab.wday ) - 1 )
		and app.session:isToday( curTime ) then -- 跨天到周刷新时间点?
		local addNum = tonumber( GD:getSystemPar("charmweeklyaddcount", 35) )
		-- 工会技能  锦上添花
		local guildModel = app:getInst("NewguildModel")
		if guildModel then
			if guildModel:isGuildCharmActive() then
				addNum = addNum + 5
			end
		end
		self.charm.num = self.charm.num + addNum
		local weeklyMaxNum = tonumber( GD:getSystemPar("charmmaxamount", 50) )
		if weeklyMaxNum < self.charm.num then
			self.charm.num = weeklyMaxNum
			UD:setCharmNumNew(true)
			self:dispatchChange("charm")
		end
	end
end

-- 好运钥匙使用情况
function Player:getCharmUsedInfo()
	local numberOfUsedToday = 0

	local lastUseTime = self.charm["lastUseTime"] -- 最后一次使用时候的时间戳
	if lastUseTime then
		if not self._charmLastUpdateTime then
			self:updateCharmLastUpdateTime()
		end
		if self._charmLastUpdateTime <= lastUseTime then -- 最后使用的时间是在今天刷新之后
			numberOfUsedToday = self.charm.useDailyNum
		else
			numberOfUsedToday = 0
		end
	end
	-- print( " =========>>>>>> Player:getCharmUsedInfo ", self.charm.num )
	return self.charm.num, numberOfUsedToday
end

return Player
